package info.demo.filter;

import java.io.ByteArrayOutputStream;

public class HexConverter {

    public static String encode(byte[] encondedBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte encodedByte : encondedBytes) {
            int i = Integer.signum(encodedByte) < 0 ? encodedByte & 0xFF : encodedByte;
            String hex = Integer.toHexString(i);
            if (hex.length() < 2)
                sb.append("0");
            sb.append(hex);
        }
        return sb.toString();
    }

    public static byte[] decode(String encodedString) {
        if (encodedString.length() % 2 != 0)
            throw new NumberFormatException("The length of the encoded string must be even");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        for (int i = 0; i < encodedString.length(); i += 2) {
            String hex = "0x"+encodedString.substring(i, i + 2);
            bos.write(Integer.decode(hex).byteValue());
        }
        return bos.toByteArray();
    }

}
